package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.AmazonStorageFeeLongterm;
import com.fowo.api.entity.TmpStorageFeeLongterm;
import com.fowo.api.mapper.AmazonStorageFeeLongtermMapper;
import com.fowo.api.mapper.TmpStorageFeeLongtermMapper;
import com.fowo.api.syncAmazon.api.StorageFeeLongTermReportService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class StorageFeeLongTermServiceImpl extends ServiceImpl<AmazonStorageFeeLongtermMapper, AmazonStorageFeeLongterm> {

    @Resource
    private TmpStorageFeeLongtermMapper tmpStorageFeeLongtermMapper;
    @Resource
    private StorageFeeLongTermReportService termReportService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    public void syncStorageFeeLongTerm() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllStorageFeeLongTerm();
        //拉数据到临时表
        termReportService.getStorageFeeLongTerm();
        //获取临时表数据
        List<TmpStorageFeeLongterm> longterms = tmpStorageFeeLongtermMapper.selectList(new QueryWrapper<TmpStorageFeeLongterm>().eq("del_flag", 0));
        List<AmazonStorageFeeLongterm> insertList = new ArrayList<>();
        if(longterms != null && longterms.size() > 0){
            for (TmpStorageFeeLongterm longterm:longterms) {
                QueryWrapper<AmazonStorageFeeLongterm> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("del_flag",0);
                orderWrapper.eq("sid",longterm.getSid());
                orderWrapper.eq("fnsku",longterm.getFnsku());
                orderWrapper.eq("snapshot_date",longterm.getSnapshotDate());
                int count = (int)this.count(orderWrapper);
                if(count > 0){
                    continue;
                }
                AmazonStorageFeeLongterm amazonStorageFeeLongterm = new AmazonStorageFeeLongterm();
                BeanUtils.copyProperties(longterm, amazonStorageFeeLongterm);
                amazonStorageFeeLongterm.setId(null);
                amazonStorageFeeLongterm.setCreateTime(new Date());
                insertList.add(amazonStorageFeeLongterm);
            }
            List<List<AmazonStorageFeeLongterm>> partition = Lists.partition(insertList, 200);
            for (List<AmazonStorageFeeLongterm> amazonStorageFeeLongterms:partition) {
                this.saveBatch(amazonStorageFeeLongterms);
            }
        }
    }


}
